import Taro from "@tarojs/taro";
//验证服务器返回结果
import fetch from './fetch'
import SetMD5Data from './SetMD5Data'

function VERIFY_CODE(CODE, codeStr = '') {
  let _ISPATH = false
  if (typeof codeStr === 'string') {
    //验证兼容多个code
    const CODEARR = codeStr.split(',')
    CODEARR.map((val) => {
      if (Number(val) === Number(CODE)) {
        _ISPATH = true
      }
    })
    return _ISPATH
  } else {
    return Number(codeStr) === Number(CODE)
  }
}



function myfetch({ url, data, method, CODE }) {
  return new Promise((resolve, reject) => {
    let contentType = data.contentType || 'application/x-www-form-urlencoded'
    let responseType = data.responseType || ''
    delete data['contentType']
    delete data['responseType']

    let upData = {
      url: url,
      method: method,
      data: SetMD5Data(data),
      responseType: responseType,
      header: {
        'content-type': contentType
      },
    }
    interface typeResData {
      data: {
        code: string | number;
        msg: string
      }
    }
    fetch(upData).then((res: typeResData) => {
      const resData = res.data
      if (VERIFY_CODE(res.data.code, CODE)) {
        //验证CODE
        resolve(resData)
      } else {
        reject(resData)
        Taro.showToast({ title: resData.msg || ('未知错误:' + JSON.stringify(resData)), icon: 'none' })
      }
    }, (res) => {
      const resData = res.data
      reject(resData)
      Taro.showToast({ title: resData.msg || ('未知错误:' + JSON.stringify(resData)), icon: 'none' })
    })
  })
}

export default myfetch